<template>
  <el-drawer v-model="resultDrawer" title="测试数据" direction="rtl" :with-header="false" size="50%">
    <splitpanes class="default-theme" horizontal style="height: 100%">
      <pane min-size="20" size="70">
        <el-tabs type="border-card">
          <el-tab-pane :label="tab.nodeName" v-for="tab in resultData" :key="tab.nodeId">
            <table>
              <tr>
                <th v-for="outputName in tab.outputNames" v-text="outputName" :key="outputName"></th>
              </tr>
              <tr v-for="(value, index) in tab.values" :key="index" @click="detail(tab.outputNames, value)">
                <td v-for="(val, ind) in value" v-text="val" :key="index + '-' + ind" style="width: fit-content"></td>
              </tr>
            </table>
          </el-tab-pane>
        </el-tabs>
      </pane>
      <pane min-size="20" size="30">
        <LogPreview border :height="400" :value="logText" />
      </pane>
    </splitpanes>

    <el-drawer v-model="innerDrawer" title="详细数据" direction="ltr" :append-to-body="true" size="50%">
      <div :title="outputName" name="1" v-for="(outputName, index) in detailObj.columns" :key="outputName">
        <div style="float: right; line-height: 32px; padding: 10px">
          <el-button type="primary" link @click="previewText(detailObj.data[index])"> 预览HTML </el-button>
          <el-button type="primary" link @click="copyText(detailObj.data[index])"> 复制 </el-button>
          <!-- <el-button type="primary" link> 隐藏 </el-button> -->
        </div>
        <h4 v-text="outputName" style="background-color: aliceblue; line-height: 32px; padding: 10px; margin: 0"></h4>
        <div style="word-wrap: break-word; border: 1px solid aliceblue; padding: 10px; line-height: 20px; font-size: 14px" v-text="detailObj.data[index]"></div>
      </div>
      <el-drawer v-model="htmlDrawer" title="预览" direction="rtl" :append-to-body="true" size="80%">
        <div v-html="htmlData" v-if="changePreview"></div>
        <pre v-text="htmlData" v-else></pre>
        <template #footer>
          <div style="flex: auto">
            <span v-text="'预览已去除script脚本，不会加载原网站脚本'" style="margin: 20px; color: #e15300"></span>
            <el-button @click="changePreview = true">UI</el-button>
            <el-button @click="changePreview = false">文本</el-button>
          </div>
        </template>
      </el-drawer>
    </el-drawer>
  </el-drawer>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { sendWebsocket, closeWebsocket } from "@/utils/websocket.js";
// import Codemirror from "codemirror-editor-vue3";
import { ElMessage } from "element-plus";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import LogPreview from "./result-log-preview.vue";
const logText = ref();
const isLoading = ref(true);
const resultData: any = ref([]);
const resultDrawer = ref(false);
const innerDrawer = ref(false);
const htmlDrawer = ref(false);
const htmlData = ref("");
const changePreview = ref(true);
const detailObj = reactive({
  columns: [],
  data: []
});
const previewText = (val: string) => {
  htmlDrawer.value = true;
  let text = val;
  htmlData.value = text.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "");
};
const show = () => {
  resultDrawer.value = true;
};
const copyText = (val: string) => {
  const textarea = document.createElement("textarea");
  textarea.value = val;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
  ElMessage.success({
    message: "成功",
    duration: 2000
  });
};
const detail = (columns: any, dataForm: any) => {
  detailObj.columns = columns;
  detailObj.data = dataForm;
  innerDrawer.value = true;
};
const run = (xmlCode: string, params: string) => {
  resultDrawer.value = true;
  // this.activeConsole = '1'
  resultData.value = [];
  // this.isLoading = true
  // 防止用户多次连续点击发起请求，所以要先关闭上次的ws请求。
  closeWebsocket();
  if (xmlCode) {
    // 跟后端协商，需要什么参数数据给后台
    const obj = {
      eventType: "test",
      message: xmlCode,
      params: params
    };
    // 发起ws请求
    sendWebsocket(`ws://${window.SITE_CONFIG.apiURL}/ws`, obj, wsMessage, wsError);
  }
};
// const sendWebsocket = () => {

// }
// ws连接成功，后台返回的ws数据，组件要拿数据渲染页面等操作
const wsMessage = (data: any) => {
  resultDrawer.value = true;
  // 这里写拿到数据后的业务代码
  if (data && data.eventType === "output") {
    const element = data.message;
    const obj = resultData.value.filter((item: any) => element.nodeId === item.nodeId);
    if (obj && obj.length > 0) {
      resultData.value
        .filter((fil: any) => element.nodeId === fil.nodeId)
        .map((item: any) => {
          item.values.push(element.values);
        });
    } else {
      resultData.value.push({
        nodeId: element.nodeId,
        nodeName: element.nodeName,
        outputNames: element.outputNames,
        values: [element.values]
      });
    }
  } else if (data && data.eventType === "log") {
    const message = data.message;
    logText.value = message;
    // console.log(message);
    // logText.value = data.timestamp + " [ " + message.level + " ] " + message.message + "\n";
  } else if (data && data.eventType === "finish" && resultData.value.length > 0) {
    isLoading.value = false;
    // this.activeConsole = "tab_0";
    // this.$refs.consoleTabContent.scrollTop = 0
  }
};
// ws连接失败，组件要执行的代码
const wsError = (e: any) => {
  console.error(e);
  // this.isLoading = false
  // 比如取消页面的loading
};
defineExpose({
  run,
  show
});
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

table caption {
  font-size: 2em;
  font-weight: bold;
  margin: 1em 0;
}

th,
td {
  border: 1px solid #999;
  text-align: center;
  padding: 4px 0;
  white-space: nowrap; /* 不换行显示文本 */
  overflow: hidden; /* 隐藏溢出部分 */
  text-overflow: ellipsis; /* 使用省略号表示溢出部分 */
  min-width: 14px;
}
table tr th {
  background-color: rgba(0, 0, 0, 0.1);
}
table thead tr {
  background-color: #008c8c;
  color: #fff;
}

table tbody tr:nth-child(odd) {
  background-color: #eee;
}

table tbody tr:hover {
  background-color: #ccc;
}

table tbody tr td:first-child {
  color: #f40;
}

table tfoot tr td {
  text-align: right;
  padding-right: 20px;
}
</style>
